﻿namespace Reviewer.Business.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Reviewer.Entities.Services;
    using Reviewer.Entities;
    using Reviewer.Data;
    using System.Reflection;
    using IQToolkit;
    using Reviewer.Entities.MetadataInfo;
    using System.Web;
    using System.Web.Caching;
    using System.Linq.Expressions;
    using Reviewer.Utilities;

    /// <summary>
    /// Metadata service
    /// </summary>
    /// <typeparam name="T">Metadata newsType</typeparam>
    public class MetadataService<T> : IMetadataService<T> where T : class,IMetadataType, new()
    {
        private IEntityTable<T> dataContext = new ReviewerDBContext().GetMetadataTable<T>();
        private string CacheKey;

        public MetadataService()
        {
            string typeName = typeof(T).Name;
            this.CacheKey = "CacheKey_" + typeName;
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns></returns>
        public ICollection<T> GetAll()
        {
            ICollection<T> allItems = null;
            if (HttpContext.Current != null)
            {
                allItems = HttpContext.Current.Cache[this.CacheKey] as ICollection<T>;
            }

            if (allItems == null)
            {
                allItems = dataContext.ToReadOnly();
                Type tType = typeof(T);
                MetadataTypeAttribute attribute = Attribute.GetCustomAttribute(tType, typeof(MetadataTypeAttribute)) as MetadataTypeAttribute;
                if (attribute != null)
                {
                    if (!String.IsNullOrEmpty(attribute.SortColumn))
                    {
                        PropertyInfo property = typeof(T).GetProperty(attribute.SortColumn);
                        if (property != null)
                        {
                            allItems = allItems.AsQueryable<T>().OrderBy(t => property.GetValue(t).ToString(), new InvariantStringComparer()).ToReadOnly<T>();
                        }
                    }
                }

                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Cache.Add(this.CacheKey, allItems, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0, 0, 0), CacheItemPriority.Default, null);
                }
            }

            return allItems;
        }

        /// <summary>
        /// Gets the specified item id.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <returns></returns>
        public T Get(int itemId)
        {
            return dataContext.FirstOrDefault(t => t.Id.Equals(itemId));
        }

        /// <summary>
        /// Saves the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public T Save(T entity)
        {
            try
            {
                int entityId = entity.Id;
                if (entityId <= 0)
                {
                    entityId = dataContext.Insert(entity, L => L.Id);
                }
                else
                {
                    dataContext.InsertOrUpdate(entity);
                }

                return dataContext.FirstOrDefault(t => t.Id.Equals(entityId));
            }
            finally
            {
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Cache.Remove(this.CacheKey);
                }
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposeManagedResources"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        private void Dispose(bool disposeManagedResources)
        {
        }
    }
}
